package com.mmall.controller.protal;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.Map;

/**
 * Created By 陈吉鑫
 * on 9:47 2017/9/2
 */
@Controller
@RequestMapping("/order/")
public class OrderController {

    private static final Logger logger= LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private IOrderService iOrderService;


    /**
     * 创建订单
     * @param session
     * @param shippingId
     * @return
     */
    @RequestMapping("create.do")
    @ResponseBody
    public ServerResponse create(HttpSession session,Integer shippingId){
        User user=(User)session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            //用户不存在 需要强制登录
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.createOrder(user.getId(),shippingId);
    }

    /**
     * 取消对应订单号的订单
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("cancel.do")
    @ResponseBody
    public ServerResponse cancel(HttpSession session,Long orderNo){
        User user=(User)session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            //用户不存在 需要强制登录
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.cancel(user.getId(),orderNo);
    }

    /**
     * 得到登录用户中购物车中所有被选中的购物详情
     * @param session
     * @return
     */
    @RequestMapping("get_order_cart_product.do")
    @ResponseBody
    public ServerResponse getOrderCartProduct(HttpSession session){
        User user=(User)session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            //用户不存在 需要强制登录
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderCartProduct(user.getId());
    }
    /**
     * 前端用户查看其中一个订单详情
     * @param session
     * @return
     */
    @RequestMapping("get_order_detail.do")
    @ResponseBody
    public ServerResponse getOrderDetail(HttpSession session,Long orderNo){
        User user=(User)session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            //用户不存在 需要强制登录
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderDetail(user.getId(),orderNo);
    }

    /**
     * 前端用户查看所有订单详情  带分页
     * @param session
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("list.do")
    @ResponseBody
    public ServerResponse list(HttpSession session,Integer pageNum,Integer pageSize){
        User user=(User)session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            //用户不存在 需要强制登录
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderList(user.getId(),pageNum,pageSize);
    }



    /**
     * 通过订单号给前端返回 订单号和二维码
     * @param session
     * @param orderNo
     * @param request
     * @return
     */
    @RequestMapping("pay.do")
    @ResponseBody
    public ServerResponse pay(HttpSession session, Long orderNo, HttpServletRequest request){
        User user=(User)session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            //用户不存在 需要强制登录
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        //拿到项目中的upload文件夹的路径
        String path=request.getSession().getServletContext().getRealPath("upload");
        return iOrderService.pay(orderNo,user.getId(),path);
    }

    /**
     * 支付宝回调验证 以及更改相关表数据
     * @param request
     * @return
     */
    @RequestMapping("alipay_callback.do")
    @ResponseBody
    public Object alipayCallBack(HttpServletRequest request){
        Map<String,String> params= Maps.newHashMap();
        Map requestParams=request.getParameterMap();
        for(Iterator item=requestParams.keySet().iterator();item.hasNext();){
            String name=(String)item.next();
            String[] values=(String[])requestParams.get(name);
            String valueStr="";
            for(int i=0;i<values.length;i++){
                valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
            }
            params.put(name,valueStr);
        }
        logger.info("支付宝回调，sign:{},trade_status:{},参数{}",params.get("sign"),params.get("trade_status"),params.toString());
        //***非常重要 验证回调的正确性，并且验证是不是支付宝发的，而且还要避免重复通知***
        params.remove("sign_type");
        try {
            //验证的参数有回调参数 支付宝公钥 字符编码 密钥类型
            boolean alipayRSACheckedV2= AlipaySignature.rsaCheckV2(params,"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvWM9bn5jWCCGePp/Qc8h8y0E8tvdDMQpn+yZ/w8XzExJ/dfRcBRCYGT+hQOGmgipgib5pVA8lvGSEnwNlRvm27WBsUe7KWpyrdV4+8ni8Vk5qkU/xmPr7IqXo8ppUCPoM2vWlhMPNNEcs2lZnb3fknAYp9P6T/w/fBAOm4+p1RmeXGj739St+QRdfBK0Hs7B3kq+93+eK04MILD1bVSSG2yuiSZI/W8wQrsbsTGVtwZrFsnEL0Sc/UDRq58mvoNpKI+5uib/oLv4aKgH9a2zwpajgI9yz15fF7uwmPJDA9FSNcOHTYQ7QOyzK15YnB9LeiPVV1htFsmhmFzBN0qN1QIDAQAB","UTF-8","RSA2");
            if(!alipayRSACheckedV2) {
                return ServerResponse.createByErrorMessage("非法请求 寻求网警帮助");
            }
            logger.info("回调的正确性:"+alipayRSACheckedV2);
        } catch (AlipayApiException e) {
            logger.error("支付宝回调异常",e);
        }

        ServerResponse serverResponse=iOrderService.aliCallBack(params);
        if(serverResponse.isSuccess()){
            return Const.ApilayCallback.RESPONSE_SUCCESS;
        }
        return Const.ApilayCallback.RESPONSE_FAILED;
    }

    /**
     * 跟前端约定 订单付款完成返回true 未付款为false
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("query_order_pay_status.do")
    @ResponseBody
    public ServerResponse<Boolean> queryOrderPayStatus(HttpSession session, Long orderNo){
        User user=(User)session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            //用户不存在 需要强制登录
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        ServerResponse serverResponse=iOrderService.queryOrderPayStatus(user.getId(),orderNo);
        if(serverResponse.isSuccess()){
            return ServerResponse.createBySuccess(true);
        }
        return ServerResponse.createBySuccess(false);
    }








}
